package cn.exrick.manager.service.hotclassload;

import cn.exrick.manager.hotclassload.BaseManager;
import com.google.common.collect.Maps;

import java.io.File;
import java.util.Map;

public class BaseManagerFactory {

    private static Map<String, LoadInfo> loadInfoMap = Maps.newHashMap();

    private static final String CLASS_PATH = "C:\\work\\hilife\\hilife-finance\\hilife-finance-provider\\target\\test-classes\\";

    public static final String MY_CLASS = "com.hilife.finance.service.MyManager";

    public static BaseManager getBaseManager(String className) {
        try {
            File loadFile = new File(CLASS_PATH + className.replaceAll("\\.", "/") + ".class");
            long lastModifyTime = loadFile.lastModified();
            System.out.println("当前类最后的加载时间：" + lastModifyTime);
            if (loadInfoMap.get(className) == null) {
                System.out.println("第一次加载类");
                loadClass(className, lastModifyTime);
            } else if (lastModifyTime != loadInfoMap.get(className).getLastLoadTime()) {
                System.out.println("类发生变化，重新加载");
                loadClass(className, lastModifyTime);
            }
            return loadInfoMap.get(className).getBaseManager();
        } catch (Exception se) {
            return null;

        }
    }

    private static void loadClass(String className, long lastModifyTime) {
        MyClassLoader myClassLoader = new MyClassLoader();
        Class<?> targetClass = null;
        try {
            targetClass = myClassLoader.loadClass(className);
            BaseManager baseManager = newInstance(targetClass);
            LoadInfo loadInfo = new LoadInfo(myClassLoader, lastModifyTime);
            loadInfo.setBaseManager(baseManager);
            loadInfoMap.put(className, loadInfo);
        } catch (Exception se) {

        }
    }

    private static BaseManager newInstance(Class<?> loadClass) throws Exception {
        return (BaseManager) loadClass.getConstructor(new Class[]{}).newInstance(new Object[]{});
    }
}
